/**
 * 
 */
package tk.sunlatus.project.usermanage.dao.impl;

import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import tk.sunlatus.project.common.constants.SunlatusConstants;
import tk.sunlatus.project.common.domain.Page;
import tk.sunlatus.project.common.domain.ProcessResult;
import tk.sunlatus.project.common.mappers.UserMapper;
import tk.sunlatus.project.security.key.KeyManager;
import tk.sunlatus.project.usermanage.dao.UserDao;
import tk.sunlatus.project.usermanage.domain.User;

/**
 * 用户管理持久化，mybatis实现
 * 
 * @author sunlotus
 * 
 */
public class UserDaoMyBatisImpl implements UserDao {
    private SqlSessionFactory sqlSessionFactory = null;

    /**
     * {@inheritDoc}
     * 
     * @see tk.sunlatus.project.usermanage.dao.UserDao#queryByID(java.lang.String)
     */
    public User queryByID(String userID) {

        SqlSession sqlSession = null;
        try {
            sqlSession = sqlSessionFactory.openSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

            return userMapper.queryByUserID(userID);
        } finally {
            sqlSession = sqlSessionFactory.openSession();
        }

    }

    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    public SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    @Override
    public boolean saveUser(User user) {
        String keySalt = user.getUserID();
        user.setSalt(KeyManager.mixKeyAndSalt(SunlatusConstants.EncodeConstant.KEY_IDEA,
            SunlatusConstants.EncodeConstant.KEY_IDEA_SIZE, keySalt));

        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        userMapper.saveUser(user);
        // 清除用户密码
        clearPasswordInfo(user);

        return true;
        // if (user.getAuthInfo() != null) {
        // userMapper.saveAuthInfo(user.getAuthInfo());
        // }
    }

    private void clearPasswordInfo(User user) {
        if (user == null) {
            return;
        }
        user.setPassword(null);
        user.setInfoPwd(null);
        user.setTradPwd(null);

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean removeByID(String userID) {
        SqlSession sqlSession = null;

        try {
            sqlSession = sqlSessionFactory.openSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

            userMapper.removeUer(userID);
            return true;
        } finally {
            closeSession(sqlSession);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ProcessResult batchSaveUser(User[] users) {
        return batchSaveUser(Arrays.asList(users));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ProcessResult batchSaveUser(Collection<User> users) {
        // TODO 批量添加用户
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ProcessResult batchRemoveUsers(String[] userIDs) {
        return batchRemoveUsers(Arrays.asList(userIDs));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ProcessResult batchRemoveUsers(Collection<String> userIDs) {
        // TODO 批量删除用户
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean deregistration(User user) {
        // TODO 注销用户
        SqlSession sqlSession = null;
        try {
            sqlSession = sqlSessionFactory.openSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

            int result = userMapper.deregistration(user);
            return result == 1;
        } finally {
            closeSession(sqlSession);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ProcessResult deregistrationUsers(User[] users) {
        return deregistrationUsers(Arrays.asList(users));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ProcessResult deregistrationUsers(Collection<User> users) {
        // TODO 批量注销用户
        return null;
    }

    @Override
    public List<User> queryUserList(User user, Page page) {
        SqlSession sqlSession = null;
        String userID = "%";
        String userName = "%";
        int offset = 0;
        int length = 10;
        try {
            sqlSession = sqlSessionFactory.openSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

            if (user != null) {
                userID = StringEscapeUtils.escapeSql(user.getUserID()).replace("%", "\\%").replace("_", "\\_") + userID;
                userName = StringEscapeUtils.escapeSql(user.getName()).replace("%", "\\%").replace("_", "\\_")
                    + userName;
            }
            if (page != null) {
                offset = page.getPageNum() * page.getPageSize();
                length = page.getPageSize();
            }

            return userMapper.queryByCondation(userID, userName, offset, length);
        } finally {
            closeSession(sqlSession);
        }
    }

    private void closeSession(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }

    @Override
    public User updateUser(User user) {
        // TODO 注销用户
        SqlSession sqlSession = null;
        try {
            sqlSession = sqlSessionFactory.openSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

            int result = userMapper.modifyUser(user);
            if (result == 1) {
                // TODO log update success;
            } else {
                // TODO log update failed;
            }
            return user;
        } finally {
            closeSession(sqlSession);
        }
    }

    @Override
    public User deleteUser(User user, boolean deleteFlag) {
        if (deleteFlag) {
            removeByID(user.getUserID());
        } else {
            Date removeDate = new Date(System.currentTimeMillis() + SunlatusConstants.SysConstant.INFO_KEEP_TIME);
            user.setExpireDate(removeDate);
            user.setStatus(SunlatusConstants.UserStatus.DEREGISTER);
            deregistration(user);
        }
        return null;
    }
}
